package com.yf.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.yf.entity.SysUser;
import com.yf.service.UserService;

public class MyRealm extends AuthorizingRealm {
	
	@Autowired
	private UserService userService;

	/**
	 * 权限认证
	 * @author yephone
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String name=(String)principals.fromRealm(getName()).iterator().next();
		SysUser user = userService.getUserByName(name);
		 if (name != null && !"".equals(name)) {  
	            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	            info.addRole(user.getRoles());
	            return info;
		 }
		return null;
	}

	/**
	 * 登录认证，并将user写入session
	 * @author yephone
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
		SimpleAuthenticationInfo info=null;
		SysUser user=null;
		UsernamePasswordToken token=(UsernamePasswordToken)at;
		String name=token.getUsername(); 
		if (name != null && !"".equals(name)) {  
            user = userService.getUserByName(name);  
            if (user != null) {  
                info= new SimpleAuthenticationInfo(user.getName(), user.getPassword(), this.getName());  
            }  
        }
		Session session=SecurityUtils.getSubject().getSession();
		session.setAttribute("user", user);
		return info;
	}

}
